package com.blinddate.utils;

import com.alibaba.fastjson.JSONObject;
import com.blinddate.properties.WeChatProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class WeChatUtil {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;
    private String gettoken(){
        String key="token";
        String accesstoken=new String();
        if(redisTemplate.opsForValue().get(key)==null){
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+weChatProperties.getAppid()+"&secret="+weChatProperties.getSecret();
            String result = HttpClientUtil.doGet(url, null);
            JSONObject jsonObject = JSONObject.parseObject(result);
            accesstoken = jsonObject.getString("access_token");
            redisTemplate.opsForValue().set(key,accesstoken,7200, TimeUnit.SECONDS);//存入redis 设置2小时过期
        }else {
            accesstoken= (String) redisTemplate.opsForValue().get(key);
        }
        return  accesstoken;
    }
    public String getwxcode(Long id){
        log.info("生成用户id为：{}的二维码",id);
        String accesstoken=gettoken();
        Map<String, Object> paraMap = new HashMap<>();
        //二维码携带参数 不超过32位 参数类型必须是字符串
        paraMap.put("scene", "userId="+id.toString());
        //二维码跳转页面
        paraMap.put("page","pages/home/home");
        //二维码的宽度
        paraMap.put("width", 450);
        //自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调
        paraMap.put("auto_color", false);
        //是否需要透明底色， is_hyaline 为true时，生成透明底色的小程序码
        paraMap.put("is_hyaline", false);
        //要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"
        paraMap.put("env_version", "trial");
        //检查page 是否存在，为 true 时 page 必须是已经发布的小程序存在的页面（否则报错）；为 false 时允许小程序未发布或者 page 不存在， 但page 有数量上限（60000个）请勿滥用
        paraMap.put("check_path", false);
        System.out.println(paraMap);
        byte[] resultewm = HttpClientUtil.getQrCodeByParam("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accesstoken, paraMap);
        String name= "usercodesrc"+id+".jpg";
        String ewmpath=aliOssUtil.upload(resultewm,name);
        return ewmpath;
    }
}
